//
//  RightMenuView.m
//  NOAHWM
//
//  Created by Ryan on 13-5-28.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "RightMenuView.h"
#import "NYMemberCenterDataManager.h"
#import "JSON.h"
#import "MenuDataManager.h"
#import "RightMenuViewCell.h"

#define kLocalMenuFileName @"LeftMenu"

@interface RightMenuView()

@property (nonatomic, retain) NSArray *properties;
@property (nonatomic, retain) NSArray *localMenuArray;

@end

@implementation RightMenuView

@synthesize menuHeaderView,menuTableView,menuFootView;
@synthesize properties;
@synthesize isRefreshInfoForOthers;
@synthesize localMenuArray;


- (RightMenuHeaderView *)menuHeaderView
{
    if(nil == menuHeaderView)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"RightMenuHeaderView" owner:self options:nil];
        menuHeaderView = [[nibs lastObject] retain];
    }
    return menuHeaderView;
}

- (RightMenuFootView *)menuFootView
{
    if(nil == menuFootView)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"RightMenuFootView" owner:self options:nil];
        menuFootView = [[nibs lastObject] retain];
    }
    return menuFootView; 
}

- (void)callServerToGetPersonalInfo
{
    NSString *suburl = [NSString stringWithFormat:kPersonalInfoUrl,@"jsonp",[NYMemberCenterDataManager sharedManager].loginMember.accountId];
    suburl = [suburl stringByAppendingString:@"app000006"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:nil];
}

#pragma mark - Notification methods
- (void)refreshPersonalInfoWithNotification:(NSNotification *)notification
{
//    self.isRefreshInfoForOthers = YES;
    [self callServerToGetPersonalInfo];
}

- (void)refreshApplyAuthWithNotification:(NSNotification *)notification
{
    if([[NYMemberCenterDataManager sharedManager].loginMember.is_auth isEqualToString:@"1"])
        self.menuHeaderView.applyAuthButton.enabled = NO;
    else
        self.menuHeaderView.applyAuthButton.enabled = YES;
}

- (void)reduceReminderNum:(NSNotification *)notification
{
    int tmp = [[NYMemberCenterDataManager sharedManager].loginMember.remind_count integerValue];
    tmp--;
    [NYMemberCenterDataManager sharedManager].loginMember.remind_count = [NSNumber numberWithInt:tmp];
    [self.menuTableView reloadData];
}

#pragma mark - UIView methods

- (void)awakeFromNib
{
    [super awakeFromNib];

    self.menuTableView.tableHeaderView = self.menuHeaderView;
    self.menuTableView.tableFooterView = self.menuFootView;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshPersonalInfoWithNotification:) name:kRefreshPersonalInfoNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshApplyAuthWithNotification:) name:kRefreshApplyAuthNotificaiton object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getMenuSucceedWithNotification:) name:kGetMenuSucceedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reduceReminderNum:) name:kMyReminderReduceNotification object:nil];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:kLocalMenuFileName ofType:@"plist"];
    self.localMenuArray = [NSArray arrayWithContentsOfFile:path];
    
    if(nil != [NYMemberCenterDataManager sharedManager].loginMember.accountId &&
       ![[NYMemberCenterDataManager sharedManager].loginMember.accountId isEqualToString:@""])
        [self refreshPersonalInfoWithNotification:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [localMenuArray release];
    [properties release];
    [menuTableView release];
    [menuHeaderView release];
    [menuFootView release];
    [super dealloc];
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.properties.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cellIdentify";
    RightMenuViewCell *rightMenuCell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if(nil == rightMenuCell)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"RightMenuViewCell" owner:self options:nil];
        rightMenuCell = [nibs lastObject];
        UIImageView *bgView = [[UIImageView alloc] init];
        bgView.image = [UIImage imageNamed:@"list_highlighted_new@2x.png"];
        rightMenuCell.selectedBackgroundView = bgView;
        [bgView release];
        
    }
    
    NYMenu *nym = [self.properties objectAtIndex:indexPath.row];
    NSDictionary *localDict = nil;
    for(NSDictionary *dict in self.localMenuArray)
    {
        if([[dict objectForKey:@"menuName"] isEqualToString:nym.funcName])
        {
            localDict = dict;
            break;
        }
    }
    rightMenuCell.nameLabel.text = nym.funcName;
    rightMenuCell.accImageView.image = [UIImage imageNamed:[localDict objectForKey:@"menuIconNormal"]];
    rightMenuCell.accImageView.highlightedImage = [UIImage imageNamed:[localDict objectForKey:@"menuIconHighlighted"]];
    if([nym.funcName isEqualToString:@"我的提醒"])
    {
        if([[NYMemberCenterDataManager sharedManager].loginMember.remind_count integerValue] <= 0)
        {
            rightMenuCell.remindCountImageView.hidden = YES;
            rightMenuCell.remindCountLabel.hidden = YES;
        }
        else
        {
            rightMenuCell.remindCountLabel.hidden = NO;
            rightMenuCell.remindCountImageView.hidden = NO;
            
            NSString *remindString = [NSString stringWithFormat:@"%@", [NYMemberCenterDataManager sharedManager].loginMember.remind_count];
            if([remindString integerValue] > 99)
            {
                remindString = @"99+";
            }
            rightMenuCell.remindCountLabel.text = remindString;
        }
    }
    else
    {
        rightMenuCell.remindCountLabel.hidden = YES;
        rightMenuCell.remindCountImageView.hidden = YES;
    }
    return rightMenuCell;
}

#pragma mark - UITableViewDelegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NYMenu *nym = [self.properties objectAtIndex:indexPath.row];
    NSDictionary *localDict = nil;
    for(NSDictionary *dict in self.localMenuArray)
    {
        if([[dict objectForKey:@"menuName"] isEqualToString:nym.funcName])
        {
            localDict = dict;
            break;
        }
    }
    if([[localDict objectForKey:@"menuNeedLogin"] boolValue])
    {
        //当前菜单需要手势密码同时用户未解过手势密码同时用户手势密码是打开状态
        NSDictionary *userDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:kIsGestureAuthed];
        NSString *isopen = [userDict objectForKey:[NYMemberCenterDataManager sharedManager].loginMember.accountId];
        
        if(![isopen isEqualToString:@"1"] &&
           [[NYMemberCenterDataManager sharedManager].loginMember gestureOpen])
        {
            lockPage = kUserReminderPage;
            //需要手势密码打开的菜单
            [self refreshPersonalInfoResponseWithNotification:nil];
            return;
        }
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:[localDict objectForKey:@"menuNotification"] object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:kHideMenuNotification object:nil];
}


#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        //保存获取的个人信息
        [NYMemberCenterDataManager sharedManager].loginMember.comper_point = [dict objectForKey:@"comper_point"];
        [NYMemberCenterDataManager sharedManager].loginMember.phoneNum = [dict objectForKey:@"account_mobile"];
        
        [NYMemberCenterDataManager sharedManager].loginMember.userName = [dict objectForKey:@"user_name"];
        [NYMemberCenterDataManager sharedManager].loginMember.address = [dict objectForKey:@"account_address"];
        [NYMemberCenterDataManager sharedManager].loginMember.fp_mobile = [dict objectForKey:@"fp_mobile"];
        [NYMemberCenterDataManager sharedManager].loginMember.fp_name = [dict objectForKey:@"fp_name"];
        [NYMemberCenterDataManager sharedManager].loginMember.status = [dict objectForKey:@"account_status"];
        [NYMemberCenterDataManager sharedManager].loginMember.memberCardType = [dict objectForKey:@"member_card_type"];
        [NYMemberCenterDataManager sharedManager].loginMember.accountName = [dict objectForKey:@"account_name"];
        [NYMemberCenterDataManager sharedManager].loginMember.gesture_password = [dict objectForKey:@"gesture_password"];
        [NYMemberCenterDataManager sharedManager].loginMember.is_gesture_password = [dict objectForKey:@"is_user_gesture_password"];
        [NYMemberCenterDataManager sharedManager].loginMember.userIcon = [dict objectForKey:@"account_image_url"];
        [NYMemberCenterDataManager sharedManager].loginMember.custom_service_phone = [dict objectForKey:@"custom_service_phone"];
        [NYMemberCenterDataManager sharedManager].loginMember.remind_count = [dict objectForKey:@"remind_count"];
        //刷新当前用户页面
        //header 刷新
        [self.menuHeaderView reloadData];
        //footer 刷新
        self.menuFootView.serviceButton.hidden = NO;
        [self.menuFootView.serviceButton setTitle:[NSString stringWithFormat:@"客服热线: %@",[NYMemberCenterDataManager sharedManager].loginMember.custom_service_phone] forState:UIControlStateNormal];
        //content 刷新
        [self.menuTableView reloadData];
//        [[NSNotificationCenter defaultCenter] postNotificationName:kReloadPersonInfoViewNotification object:nil];
//        [[RYHUDManager sharedManager] stoppedNetWorkActivity];
    }
    else
    {
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

#pragma mark - Notification methods
- (void)getMenuSucceedWithNotification:(NSNotification *)notification
{
    //self.properties = [MenuDataManager sharedManager].rightMenu;
    NSMutableArray *tmpArray = [NSMutableArray array];
    BOOL containLicaishi = NO;
    
    for (NYMenu *tmp in [MenuDataManager sharedManager].rightMenu) {
        if([tmp.funcName isEqualToString:@"专属理财师"])
        {
            containLicaishi = YES;
        }
        else
            [tmpArray addObject:tmp];
    }
    self.properties = [NSArray arrayWithArray:tmpArray];
    [self.menuTableView reloadData];
    
    if (containLicaishi) {
        self.menuFootView.finaView.hidden = NO;
    }
    else{
        self.menuFootView.finaView.hidden = YES;
    }
}

#pragma mark - public methord

- (void)refreshPersonalInfoResponseWithNotification:(NSNotification *)notification
{
    //    [NYMemberCenterDataManager sharedManager].loginMember.is_gesture_password = @"1";
    //    [NYMemberCenterDataManager sharedManager].loginMember.gesture_password = @"";
    
    //存在手势密码，打开解锁页否则设置解锁密码
    if([NYMemberCenterDataManager sharedManager].loginMember.gesture_password &&
       ![[NYMemberCenterDataManager sharedManager].loginMember.gesture_password isEqualToString:@""])
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowPatternLockViewNotification object:[NSNumber numberWithInt:1]];
    else
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowPatternLockViewNotification object:[NSNumber numberWithInt:0]];
}

@end
